<?php

declare(strict_types=1);

namespace App\Common\Middleware;

use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 跨域中间件
 * Class AllowOriginMiddleware
 */
class AllowOriginMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        if ($request->getMethod() == 'OPTIONS') {
            return $this->addCorsHeaders($response);
        }
        $response = $handler->handle($request);
        return $this->addCorsHeaders($response);
    }

    protected function addCorsHeaders(ResponseInterface $response): ResponseInterface
    {
        return $response->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
            ->withHeader('Access-Control-Allow-Headers', 'x-requested-with,request-from,DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization');
    }
}
